#include "frmmain.h"
#include "ui_frmmain.h"
#include "iconhelper.h"
#include "myhelper.h"
#include "aes_demo.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QDebug>

#include <QMenu>

frmMain::frmMain(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::frmMain)
{
    ui->setupUi(this);

    myHelper::FormInCenter(this);
    this->InitStyle();
    this->initApp();
}

frmMain::~frmMain()
{
    delete ui;
}

void frmMain::InitStyle()
{
    //设置窗体标题栏隐藏
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);
    location = this->geometry();
    max = false;
    mousePressed = false;

    //安装事件监听器,让标题栏识别鼠标双击
    ui->lab_Title->installEventFilter(this);

    IconHelper::Instance()->SetIcon(ui->btnMenu_Close, QChar(0xf00d), 10);
    IconHelper::Instance()->SetIcon(ui->btnMenu_Max, QChar(0xf096), 10);
    IconHelper::Instance()->SetIcon(ui->btnMenu_Min, QChar(0xf068), 10);
    IconHelper::Instance()->SetIcon(ui->btnMenu, QChar(0xf0c9), 10);
    IconHelper::Instance()->SetIcon(ui->lab_Ico, QChar(0xf015), 14);

    menu = new QMenu(this);
    menu->setStyleSheet("font: 10pt \"微软雅黑\";");
    QMenu * menu_style = menu->addMenu("选择皮肤");
    menu_style->addAction("黑色",this,SLOT(changeStyle()));
    menu_style->addAction("天蓝",this,SLOT(changeStyle()));
    menu_style->addAction("灰色",this,SLOT(changeStyle()));
    menu_style->addAction("海蓝",this,SLOT(changeStyle()));
}

void frmMain::initApp()
{
    ui->combSecretMode->setCurrentIndex(0);

    QRegExp regExp1(".{0,20}");
    QRegExpValidator *reg1 = new QRegExpValidator(regExp1,this);
    ui->lineName->setValidator(reg1);

    QRegExp regExp2("^[0-9]*$");
    QRegExpValidator *reg2 = new QRegExpValidator(regExp2,this);
    ui->lineUpdateNum->setValidator(reg2);
}

bool frmMain::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonDblClick) {
        this->on_btnMenu_Max_clicked();
        return true;
    }
    return QObject::eventFilter(obj, event);
}

void frmMain::mouseMoveEvent(QMouseEvent *e)
{
    if (mousePressed && (e->buttons() && Qt::LeftButton) && !max) {
        this->move(e->globalPos() - mousePoint);
        e->accept();
    }
}

void frmMain::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton) {
        mousePressed = true;
        mousePoint = e->globalPos() - this->pos();
        e->accept();
    }
}

void frmMain::mouseReleaseEvent(QMouseEvent *)
{
    mousePressed = false;
}

void frmMain::changeStyle()
{
    QAction *action = (QAction *)sender();
    QString style = action->text();
    if (style == "黑色") {
        style = "black";
    } else if (style == "天蓝") {
        style = "blue";
    } else if (style == "灰色") {
        style = "gray";
    } else if (style == "海蓝") {
        style = "navy";
    }

    //myHelper::SetStyle(style);
    myHelper::SetStyle("black");
}

void frmMain::on_btnMenu_Close_clicked()
{
    qApp->exit();
}

void frmMain::on_btnMenu_Max_clicked()
{
//    if (max) {
//        this->setGeometry(location);
//        IconHelper::Instance()->SetIcon(ui->btnMenu_Max, QChar(0xf096), 10);
//        ui->btnMenu_Max->setToolTip("最大化");
//    } else {
//        location = this->geometry();
//        this->setGeometry(qApp->desktop()->availableGeometry());
//        IconHelper::Instance()->SetIcon(ui->btnMenu_Max, QChar(0xf079), 10);
//        ui->btnMenu_Max->setToolTip("还原");
//    }
//    max = !max;
}

void frmMain::on_btnMenu_Min_clicked()
{
    this->showMinimized();
}

void frmMain::on_btnMenu_clicked()
{
    menu->exec(ui->btnMenu->mapToGlobal(QPoint(0,34)));
}

bool frmMain::read_bin_file(QString path)
{
    QString str;
    QFile file(path);

    if(file.open(QIODevice::ReadOnly)) {
        this->binFileData = file.readAll();
        file.close();
        scrFileSize = this->binFileData.size();
        str.sprintf("%d-0x%X",scrFileSize,scrFileSize);
        ui->labScrFileSize->setText(str);
        return 1;
    }else {
        ui->labScrFileSize->setText("打开文件失败");
        return 0;
    }
}

void frmMain::on_btnSelectFile_clicked()
{
    QString strstart,str,strnew;

    QString path = QFileDialog::getOpenFileName(this,"打开文件",".","Update (*.bin *.hex)");
    if(path.length() != 0) {
        ui->lineFile->setText(path);
        if(read_bin_file(path)) {
            for(int i=0;i<this->binFileData.size();i++) {
                if(i%16 == 0) {
                    strstart.sprintf("%08X",(int)i);

                }
                str.sprintf(" %02X",(quint8)this->binFileData.at(i));
                strstart.append(str);

                if((i+1)%16 == 0) {
                    strnew.append(strstart).append("\r\n");
                }
            }
            ui->textSrcFile->setText(strnew);
        }
    }
}

void frmMain::on_btnGenerateFile_clicked()
{
    QString strstart,str,strnew;
    QByteArray ba;
    bool b;

    QString srcpath = ui->lineFile->text();
    QString dstpath;

    char *array = (char *)&sw_head;
    for(uint16_t i=0;i<sizeof(sw_head_t);i++) {
        array[i] = 0;
    }

    if(srcpath.isEmpty()) {
        ui->labScrFileSize->setText("请输入正确文件路径");
        return;
    }

    if(read_bin_file(ui->lineFile->text())) {
        memcpy(sw_head.head,"update",strlen("update"));
        sw_head.updateNum = ui->lineUpdateNum->text().toInt(&b);
        ba = ui->lineName->text().toLatin1();
        strcpy(sw_head.name,ba.data());
        sw_head.fileSize = this->binFileData.size();

        QByteArray dat = ui->lineSecretKey->text().toLatin1();
        char *buff = dat.data();
        AES_SetKey((unsigned char *)buff);
        AES_EncryptInit();

        QString ss = ui->combSecretMode->currentText();
        if(ss == "NONE") {
            sw_head.encryptMode = 0;
            char *ch = this->binFileData.data();
            sw_head.fileCrc = myHelper::CRC_calc(0,(quint8 *)&ch[0],(quint8 *)&ch[this->binFileData.size()-1]);
        }else if(ss == "AES-256"){
            sw_head.encryptMode = 1;
            this->aesFileData.clear();
            quint32 cnt = this->binFileData.size();
            char *dat = this->binFileData.data();
            for(quint32 i=0;i<cnt;i+=16) {
                AES_Encrypt((unsigned char *)&dat[i]);
                this->aesFileData.append(&dat[i],16);
            }

            char *ch = this->aesFileData.data();
            sw_head.fileCrc = myHelper::CRC_calc(0,(quint8 *)&ch[0],(quint8 *)&ch[this->aesFileData.size()-1]);
            this->binFileData = this->aesFileData;
        }
    }


    sw_head.headCrc = myHelper::CRC_calc(0,(quint8 *)&array[0],(quint8 *)&array[sizeof(sw_head_t)-3]);

    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
    QString timestr = time.toString("yyyy-MM-dd hh-mm-ss"); //设置显示格式
    int first = srcpath.lastIndexOf('/');
    dstpath = srcpath.left(first+1);
    dstpath.append("update-"+ui->lineName->text()+" "+ui->lineUpdateNum->text()+" "+ui->combSecretMode->currentText()+" "+timestr+".bin");
    //qDebug()<<dstpath;

    QFile dstfile(dstpath);
    if(dstfile.exists()) {

    }else {
        dstfile.open(QIODevice::WriteOnly);
        dstfile.close();
    }

    if(dstfile.open(QIODevice::ReadWrite)) {
        QByteArray dstBinData;
        dstBinData.clear();
        dstBinData.append(array,sizeof(sw_head_t));
        dstBinData.append(binFileData);

        dstfile.write(dstBinData);

        dstfile.close();

        //G:/work/DPF/code/app/stm32f10x-template/hex/
        for(qint32 i=0;i<dstBinData.size();i++) {
            if(i%16 == 0) {
                strstart.sprintf("%08X",(int)i);
            }
            str.sprintf(" %02X",(quint8)dstBinData.at(i));
            strstart.append(str);

            if((i+1)%16 == 0) {
                strnew.append(strstart).append("\r\n");
            }
        }
        ui->textDstFile->setText(strnew);

        QString str;
        str.sprintf("0x%X",sw_head.fileCrc);
        ui->labFileCrc->setText(str);

        str.sprintf("0x%X",sw_head.headCrc);
        ui->labHeadCrc->setText(str);
    }
}
